package cn.cuilan.filter;

import cn.cuilan.utils.ErrorCode;
import cn.cuilan.utils.GlobalConstant;
import cn.cuilan.utils.Results;
import cn.cuilan.utils.TokenHandler;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Token校验过滤器
 *
 * @author zhang.yan
 */
@WebFilter(filterName = "tokenFilter", urlPatterns = "/*")
public class TokenFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("TokenFilter is init! [filterName: tokenFilter, urlPatterns: /* ]");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // JSON跨域支持
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 设置响应头为JSON数据
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 从request中获取请求uri
        String uri = request.getRequestURI();

        // 判断是否为不需要token验证的接口
        if (!isUnAuthorizationUri(uri)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Request need Authorization! uri: " + uri);
            }
            // 进行token认证
            String authorization = request.getHeader("Authorization");
            JSONObject jsonObject;

            // TODO 关闭token验证，注释掉 try {} catch {}
            /*try {
                jsonObject = TokenHandler.parseToken(authorization);

                // TODO 验证token失效时间

                Map<String, Object> tokenMap = new HashMap<>();
                tokenMap.put("userId", jsonObject.get("userId"));
                tokenMap.put("userName", jsonObject.get("userName"));

                // TODO 获取token中的参数放入request中

                servletRequest.setAttribute("tokenMap", tokenMap);
            } catch (Exception e) {
                // token认证失败
                Results results = Results.error().result(ErrorCode.AUTHORIZATION_FAIL).data("token失效!");
                jsonObject = new JSONObject(results);
                PrintWriter out = response.getWriter();
                out.write(jsonObject.toString());
                logger.error("TokenFilter doFilter parse token is failed!");
                return;
            }*/
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 验证uri是否需要token验证
     *
     * @param uri 接口名称
     * @return 如果不需要验证，则返回true；需要验证，则返回false
     */
    private boolean isUnAuthorizationUri(String uri) {
        for (String unUri : GlobalConstant.UN_AUTHORIZATION_URI) {
            if (uri.equals(unUri)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Request not need Authorization! uri: " + uri);
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        if (logger.isDebugEnabled()) {
            logger.debug("TokenFilter is destroy!");
        }
    }
}
